package com.wsd.util;


public class PagingBuilder {
	/**
	 *
	 * @param url url 例子：xxx.action?page=@page@
	 * @param pageNumber 当前页面
	 * @param pagingRange 页面区间
	 * @param max 页面总数
	 * @return
	 */
	public static String build(String url,int pageNumber,int pagingRange,int max){

		StringBuffer sb = new StringBuffer("");
		String pattern = "<a href='@url@' class='pagebar'>@pageDesc@</a>";//链接模板
		if(!"".equals(url) && url != null){
			pattern = pattern.replaceAll("@url@", url);
		}

		int middle = pagingRange/2;
		int start = pageNumber - middle;//得到起始页
		if(!isFirst(pageNumber)){//如果不是第一页，者加入第一页信息
			//sb.append(pattern.replaceAll("@page@", "1").replaceAll("@pageDesc@", "<<" ) + " ");
			sb.append(pattern.replaceAll("@page@", getPrevious(pageNumber) + "").replaceAll("@pageDesc@", "Prev" ) + " ");
		}
		int num = 0;
		for(int i = start; i<=max; i++){
			String pageLink = new String(pattern);
			if(i<= 0){
				continue;
			}
			if(num++ == pagingRange){
				break;
			}
			pageLink = pageLink.replaceFirst("@page@", i + "");
			if(i == pageNumber){
				//pageLink = pageLink.replaceFirst("@pageDesc@", "[" + i + "]");
				pageLink = "<span class=\"this-page\"> " + i + "</span>";
			}else{
				pageLink = pageLink.replaceFirst("@pageDesc@", i + "");
			}

			sb.append(pageLink + " ");
		}

		if(!isLast(pageNumber,max)){//如果不是最后一页
			sb.append(pattern.replaceAll("@page@", getNext(pageNumber,max) + "").replaceAll("@pageDesc@", "Next" ) + " ");
			//sb.append(pattern.replaceAll("@page@", max + "").replaceAll("@pageDesc@", ">>" ));
		}
		return sb.toString();
	}

	private static boolean isFirst(int pageNumber){
		return pageNumber == 1;
	}
	private static int getPrevious(int pageNumber) {
		if(pageNumber-1<=1){
			return 1;
		}else{
			return pageNumber-1;
		}
	}
	private static int getNext(int pageNumber,int max) {
		if (pageNumber + 1 >= max) {
			return max;
		}
		return pageNumber + 1;
	}
	private static boolean isLast(int pageNumber,int max) {
		return pageNumber>=max;
	}

}
